package cn.lastjune.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.lastjune.pojo.Area;
import cn.lastjune.service.AreaService;
import cn.lastjune.util.NumberUtil;
import cn.lastjune.util.Page;

@Controller
@RequestMapping("/area")
public class AreaController
{
	//这个annotation声明了容器自动注入这个对象
    @Autowired
    AreaService areaService;
    public String emptyJson = "{metaData:{totalProperty : 'total',root : "
            + "'result',fields: ['areaID','happenArea','street'" + ",'communit']},total:0, result : []}";

    //此方法处理前台/area?method=get的请求
    @RequestMapping(method = RequestMethod.GET)
    public void getAll(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        PrintWriter out = response.getWriter();
        final Page<Area> page = new Page<Area>();
        int start=request.getParameter("start")==null?0:NumberUtil.parseInt(request.getParameter("start"));
        int limit=request.getParameter("limit")==null?11:NumberUtil.parseInt(request.getParameter("limit"));
        page.setPageNo(start/limit+1);
        page.setPageSize(limit);
        final Page<Area> result = areaService.getAllArea(page);
        final List<Area> list = result.getResult();
        StringBuilder sb = new StringBuilder();
        int count = list.size();
        if (count > 0)
        {
            String jsonHead = "{" + "metaData:{" + "totalProperty : 'total'," + "root : 'result',"
                    + "fields: ['areaID','happenArea','street','communit']}," + "total:" + result.getTotalCount() + ", result : [";
            sb.append(jsonHead);

            for (Area e : list)
            {
                count--;
                sb.append("{" + "areaID : '" + e.getAreaid().toString() + "'," + "happenArea : '"
                        + e.getHappenarea().toString() + "'," + "street: '" + e.getStreet().toString() + "',"
                        + "communit: '" + e.getCommunit().toString() + "'" + "}");
                if (count > 0)
                {
                    sb.append(",");
                }
            }
            sb.append("]}");
            System.out.println(sb);
        }
        else
        {
            sb.append(emptyJson);
        }
        String sbnew = sb.toString().replace("null", "");
        out.print(sbnew);
        out.flush();
    }

    @RequestMapping(method = RequestMethod.POST)
    public void modifyArea(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        PrintWriter out = response.getWriter();
        response.setHeader("Charset", "UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/json"); // 解决后台数据中文乱码
        response.setCharacterEncoding("UTF-8");
        String method = request.getParameter("method");
        String areaID = request.getParameter("areaID");
        String happenarea = request.getParameter("happenArea");
        String street = request.getParameter("street");
        String communit = request.getParameter("communit");
        Area e = new Area();
        e.setAreaid(areaID);
        e.setHappenarea(happenarea);
        e.setStreet(street);
        e.setCommunit(communit);
        System.out.println(method);
        if ("add".equals(method))
        {
            try
            {
                areaService.insertArea(e);
                out.print("{success:true,msg:\'yes\'}");
                out.flush();
                return;
            }
            catch (Exception e2)
            {
                out.print("{success:false,msg:\'no\'},{failure:true}");
                out.flush();
                return;
            }

        }
        if ("edit".equals(method))
        {
            try
            {
                areaService.updateArea(e);
                out.print("{success:true,msg:\'yes\'}");
                out.flush();
                return;
            }
            catch (Exception e2)
            {
                out.print("{success:false,msg:\'no\'},{failure:true}");
                out.flush();
                return;
            }
        }
        if ("delete".equals(method))
        {
            try
            {
                String ids[] = request.getParameterValues("ids");
                for (String id : ids)
                {
                    areaService.deleteArea(id);
                }
                out.print("{success:true,msg:\'yes\'}");
                out.flush();
                return;
            }
            catch (Exception e2)
            {
                out.print("{success:false,msg:\'no\'},{failure:true}");
                out.flush();
                return;
            }
        }
        if("twk".equals(method))
        {
            try
            {
            	Session session = null;
            	// SQLQuery sq = ses.createSQLQuery("insert into Duck values(-1,\"gg\")");
            	// sq.executeUpdate();
            	  String sql = "select happenarea,count(happenarea) from AREA a  " +
  				"group by a.happenarea";
            	  List list=session.createSQLQuery(sql).list(); 
            	  Iterator it=list.iterator();
            	  String jsonHead = "{" + "metaData:{" + "totalProperty : 'total'," + "root : 'result',"
                  + "fields: ['happenArea','rate']}," + "total:" + list.size() + ", result : [";
            	  StringBuilder sb2 = new StringBuilder();
            	  sb2.append(jsonHead);
//            	  String[] tableName = {"Area"};
//            	  Class[] className = {Area.class};
            	  int count=list.size();
            	  HashMap<String,String> xx;
            	  for(Object o:list)
            	  {
            		  HashMap<String,String> t=(HashMap<String,String>)o;
            		  count--;
                      sb2.append("{" + "happenArea : '" + t.get("happenarea")+ "'," + "rate : '"
                              + t.get("rate") + "'" + "}");
                      if (count > 0)
                      {
                          sb2.append(",");
                      }
                  }
                  sb2.append("]}");
                  System.out.println(sb2);
                  out.print(sb2);
                  out.flush();
            }
            catch (Exception e2)
            {
                out.print("{success:false,msg:\'no\'},{failure:true}");
                out.flush();
                return;
            }
        }
    }
}
